﻿<controls:MetroWindow x:Class="SQX.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:dm="clr-namespace:SQX.ViewModel"
        xmlns:as="clr-namespace:Microsoft.AnalysisServices.AdomdClient;assembly=Microsoft.AnalysisServices.AdomdClient"
        xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
        mc:Ignorable="d" 
        Title="SQX Editor" d:DesignHeight="500" d:DesignWidth="500"  WindowStartupLocation="CenterScreen"
                      ShowIconOnTitleBar="False"
        Icon="/SQX;component/wrench1.ico" IconBitmapScalingMode="HighQuality" 
        x:Name="mainWindow" WindowState="Maximized">
    <controls:MetroWindow.RightWindowCommands>
        <controls:WindowCommands>
            <Button x:Name="settings" Click="settings_Click">
                <StackPanel Orientation="Horizontal">
                    <Rectangle Width="20" Height="20"
                   Fill="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Foreground}">
                        <Rectangle.OpacityMask>
                            <VisualBrush Stretch="Fill"
                         Visual="{StaticResource appbar_settings}" />
                        </Rectangle.OpacityMask>
                    </Rectangle> 
                    <TextBlock Text="settings" Margin="10,0,0,0" />
                </StackPanel>
            </Button>
            <Button x:Name="accentSwitcher" Click="accentSwitcher_Click">
                <StackPanel Orientation="Horizontal">
                    <Rectangle Width="20" Height="20"
                   Fill="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=Foreground}">
                        <Rectangle.OpacityMask>
                            <VisualBrush Stretch="Fill"
                         Visual="{StaticResource appbar_swap}" />
                        </Rectangle.OpacityMask>
                    </Rectangle>
                    <TextBlock Text="change accent" Margin="10,0,0,0" />
                </StackPanel>
            </Button>
        </controls:WindowCommands>
    </controls:MetroWindow.RightWindowCommands>
    <controls:MetroWindow.Resources>
        <ContextMenu x:Key="QueryContextMenu">
            <MenuItem x:Name="querySaver" Header="Save query..." Click="querySaver_Click" />
            <MenuItem x:Name="queryCloser" Header="Close tab" Click="queryCloser_Click" />
        </ContextMenu>

        <dm:AxisConverter x:Key="AxisConverter" />
        <dm:RelativeAxisConverter x:Key="RelativeAxisConverter" />
        <dm:SavedStatusToColorConverter x:Key="SavedStatusConverter" />
        <dm:ItemCountToVisibilityConverter x:Key="CountToVisibilityConverter" />
        <dm:ToolTipTemplateSelector
                x:Key="helperTipTemplateSelector"
                structureTemplate="{StaticResource structureTipTemplate}"
                functionTemplate="{StaticResource functionTipTemplate}"
                syntaxTemplate="{StaticResource syntaxTipTemplate}"
            />

        <CollectionViewSource x:Key="helpItems" Source="{Binding DataContext.QueryHelpList, ElementName=queries}"
                              Filter="CollectionViewSource_Filter"
                              />

        <Popup x:Key="QueryHelp" 
               Placement="Bottom" 
               StaysOpen="False"
               IsOpen="False"
               Height="200"
               Width="Auto"
               MinWidth="200" PopupAnimation="Fade"
               
               >
            <ListBox x:Name="hintsSelector" 
                     ScrollViewer.HorizontalScrollBarVisibility="Hidden"
                     ScrollViewer.VerticalScrollBarVisibility="Auto"
                     IsTextSearchEnabled="True"
                     FontSize="10"
                     ItemsSource="{Binding Source={StaticResource helpItems},IsAsync=True}"
                     KeyDown="hintsSelector_KeyDown"
                     ItemTemplateSelector="{StaticResource helperTipTemplateSelector}"                     
                     Background="WhiteSmoke"
                     BorderBrush="{Binding WindowTitleBrush, ElementName=mainWindow}"
                     BorderThickness="1.5" 
                     SelectedItem="{Binding Items.CurrentItem, Mode=OneWay, RelativeSource={RelativeSource Self}}" MouseDoubleClick="hintsSelector_MouseDoubleClick"
                    />               
        </Popup>
        
        <dm:ObjectExplorerTemplateSelector
            x:Key="templateSelector"
            serverTemplate="{StaticResource serverTemplate}"
            sqlServerTemplate="{StaticResource sqlServerTemplate}"
            />
    </controls:MetroWindow.Resources>

    <Grid x:Name="mainArea" DataContext="{Binding}" Background="WhiteSmoke">
        <ToolBar   x:Name="operations" Height="30" VerticalAlignment="Top">
            <Button x:Name="newMDXQuery" Click="newMDXQuery_Click">
                <StackPanel Orientation="Horizontal">
                    <Image Source="../Resources/olap.png" Margin="0,0,10,0" Width="18" Height="18"/>
                    <TextBlock Text="New MDX Query" VerticalAlignment="Center" />
                </StackPanel>
            </Button>
            <Button x:Name="newSQLQuery" Margin="10,0,0,0" Click="newSQLQuery_Click">
                <StackPanel Orientation="Horizontal" >
                    <Image Source="../Resources/sqldb.png" Margin="0,0,10,0" Width="18" Height="18"/>
                    <TextBlock Text="New SQL Query" VerticalAlignment="Center"/>
                </StackPanel>
            </Button>
            <Button x:Name="runQuery" Margin="10,0,0,0" Click="runQuery_Click">
                <StackPanel Orientation="Horizontal" >
                    <Image Source="../Resources/runquery.png" Margin="0,0,10,0" Width="18" Height="18"/>
                    <TextBlock Text="Run" VerticalAlignment="Center"/>
                </StackPanel>
            </Button>
            <Button x:Name="stopQuery" Margin="10,0,0,0"
                    IsEnabled="{Binding IsThreadActive}" Click="stopQuery_Click">
                <StackPanel Orientation="Horizontal" >
                    <Image Source="../Resources/stopquery.png" Margin="0,0,10,0" Width="18" Height="18"/>
                    <TextBlock Text="Stop" VerticalAlignment="Center"/>
                </StackPanel>
            </Button>
            <Button x:Name="saveQuery" Margin="10,0,0,0" Click="saveQuery_Click">
                <StackPanel Orientation="Horizontal" >
                    <Image Source="../Resources/savequery.png" Margin="0,0,10,0" Width="18" Height="18"/>
                    <TextBlock Text="Save" VerticalAlignment="Center"/>
                </StackPanel>
            </Button>
            <Button x:Name="openQuery" Margin="10,0,0,0" Click="openQuery_Click">
                <StackPanel Orientation="Horizontal" >
                    <Image Source="../Resources/openquery.png" Margin="0,0,10,0" Width="18" Height="18"/>
                    <TextBlock Text="Open" VerticalAlignment="Center"/>
                </StackPanel>
            </Button>
            <StackPanel Orientation="Horizontal" Margin="20,0,0,0">
                <controls:ProgressRing x:Name="Status" IsActive="{Binding IsThreadActive, Mode=OneWay}"
                            Width="15"
                            HorizontalAlignment="Right"
                         />
                <Label x:Name="statusText" Content="{Binding ThreadStatusText, Mode=OneWay}" Margin="10,0,0,0"
                       HorizontalAlignment="Right"/>
                <Label x:Name="timePassed" Content="{Binding TimePassed, Mode=OneWay}" Margin="10,0,0,0"
                       HorizontalAlignment="Right"/>
            </StackPanel>

            <ComboBox x:Name="models"
                     ItemsSource="{Binding ModelCollection}"
                     SelectedItem="{Binding ActiveModel}"
                     Visibility="{Binding Items.Count, Converter={StaticResource CountToVisibilityConverter}, Mode=OneWay, RelativeSource={RelativeSource Self}}" 
                      DropDownOpened="models_DropDownOpened"
                      DropDownClosed="models_DropDownClosed"
                     >
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding ModelName}" ToolTip="{Binding ModelName}"
                                   Margin="10,0,10,0"/>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

            <ComboBox x:Name="fontBox" 
                      ItemsSource="{Binding UIFonts}"
                      SelectedItem="{Binding EditorFontFamily}"
                      ToolTip="Query editor font setting"
                      >
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Source}" Margin="10,0,10,0" />
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
            
            <ComboBox x:Name="fontSizeBox"
                      ItemsSource="{Binding FontSizes}"
                      SelectedItem="{Binding EditorFontSize}"
                      ToolTip="Query editor font size"
                      >
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Key}" Margin="10,0,10,0" />
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
            
            <!--<TextBlock x:Name="codeLines"
                       Margin="10,0,0,0"
                       DataContext="{Binding SelectedItem, ElementName=queries}"
                       Text="{Binding Header}"
                       VerticalAlignment="Center"
                       />-->

        </ToolBar>
   
            <TabControl x:Name="queries"
                    ItemsSource="{Binding QueryCollection, UpdateSourceTrigger=PropertyChanged}" 
                    SelectionChanged="queries_SelectionChanged"
                    Width="{Binding ActualWidth, ElementName=objQueryControl, Mode=OneWay}"
                        DataContext="{Binding ActiveModel, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                        SelectedItem="{Binding ActiveQuery}"
                        Margin="0,35,0,0"
                    >
                <TabControl.Resources>
                    <Style TargetType="TabItem">
                        <Setter Property="Header" Value="{Binding Header}" />
                    <Setter Property="ContextMenu" Value="{StaticResource QueryContextMenu}" />
                    <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="TabItem">
                                    <Border Name="Border" BorderThickness="1,1,1,0" BorderBrush="Gainsboro" CornerRadius="4,4,0,0" Margin="2,0">
                                        <ContentPresenter x:Name="ContentSite"
                                        VerticalAlignment="Center"
                                        HorizontalAlignment="Center"
                                        ContentSource="Header"
                                        Margin="10,2"/>
                                    </Border>
                                    <ControlTemplate.Triggers>
                                        <Trigger Property="IsSelected" Value="True">
                                        <Setter TargetName="Border" Property="Background" Value="{Binding IsSaved, Converter={StaticResource SavedStatusConverter}}" />
                                        </Trigger>
                                        <Trigger Property="IsSelected" Value="False">
                                            <Setter TargetName="Border" Property="Background" Value="GhostWhite" />
                                        </Trigger>
                                    </ControlTemplate.Triggers>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </TabControl.Resources>
                <TabControl.ContentTemplate>
                    <DataTemplate>
                        <StackPanel x:Name="queryArea" Orientation="Horizontal"
                                    
                                    Width="{Binding ActualWidth, ElementName=queries, Mode=OneWay}">
                        <ContentControl x:Name="objExplorerSizeWrapper" Style="{StaticResource ResizablePanelStyleBottomRight}" 
                                        Width="Auto"                                       
                                        Height="{Binding Height, ElementName=queryArea}"
                                        Margin="0,0,10,0"
                                        >
                            <TreeView x:Name="objExplorer" 
                                      ItemsSource="{Binding Servers}"
                                      ItemTemplateSelector="{StaticResource templateSelector}"
                                      VirtualizingPanel.IsVirtualizing="True"
                                      DataContext="{Binding DataContext, ElementName=queries}" MouseMove="objExplorer_MouseMove"
                                      BorderBrush="LightGray"
                                      BorderThickness="1" PreviewMouseRightButtonDown="objExplorer_PreviewMouseRightButtonDown"
                                      
                                      />
                        </ContentControl>
                        <!-- dm:RichTextBoxHelper.DocumentText="{Binding Text}" -->
                            <StackPanel Orientation="Vertical" 
                                        ScrollViewer.CanContentScroll="True" 
                                        ScrollViewer.VerticalScrollBarVisibility="Auto"
                                        HorizontalAlignment="Right">
                            <ContentControl Style="{StaticResource ResizablePanelStyleBottom}" x:Name="queryEditorResizeWrapper"
                                                        MinHeight="400"
                                                >
                                <ContentControl.Width>
                                    <MultiBinding Converter="{StaticResource RelativeAxisConverter}">
                                        <Binding ElementName="queries" Path="ActualWidth" />
                                        <Binding ElementName="objExplorer" Path="ActualWidth" />
                                    </MultiBinding>
                                </ContentControl.Width>
                                <RichTextBox x:Name="queryEditor" 
                                        TextChanged="queryEditor_TextChanged"  
                                        AcceptsReturn="True"
                                        AcceptsTab="True"
                                        AllowDrop="True"
                                        PreviewKeyUp="queryEditor_PreviewKeyUp"
                                        Width="{Binding ActualWidth, ElementName=queryEditorResizeWrapper}"
                                        Height="{Binding ActualHeight, ElementName=queryEditorResizeWrapper}"
                                        HorizontalAlignment="Left" 
                                             Loaded="queryEditor_Loaded" 
                                             PreviewKeyDown="queryEditor_PreviewKeyDown" 
                                             PreviewTextInput="queryEditor_PreviewTextInput" 
                                             FontFamily="{Binding DataContext.EditorFontFamily, ElementName=mainWindow, UpdateSourceTrigger=PropertyChanged}"
                                             FontSize="{Binding SelectedItem.Value, ElementName=fontSizeBox, UpdateSourceTrigger=PropertyChanged}"                                       
                                        >
                                    <RichTextBox.CommandBindings>
                                        <CommandBinding Command="dm:Command.RTBUndo" Executed="ExecuteRTBUndo" />
                                        <CommandBinding Command="dm:Command.QuerySave" Executed="ExecuteQuerySave" />
                                    </RichTextBox.CommandBindings>
                                    <RichTextBox.InputBindings>
                                        <KeyBinding Key="Z" Modifiers="Control" Command="dm:Command.RTBUndo" />
                                        <KeyBinding Key="S" Modifiers="Control" Command="dm:Command.QuerySave" />
                                    </RichTextBox.InputBindings>
                                    <RichTextBox.Resources>
                                        <Style TargetType="{x:Type Paragraph}">
                                            <Setter Property="Margin" Value="0"/>
                                        </Style>
                                    </RichTextBox.Resources>
                                    <RichTextBox.CacheMode>
                                        <BitmapCache SnapsToDevicePixels="True" 
                                                    />
                                    </RichTextBox.CacheMode>
                                    <FlowDocument />
                                </RichTextBox>
                                   
                                </ContentControl>

                            <DataGrid ItemsSource="{Binding QueryResult}"                                               
                                                AutoGenerateColumns="True"
                                                ScrollViewer.CanContentScroll="True"
                                                Width="{Binding ActualWidth, ElementName=queryEditor}"
                                                Margin="0,10,0,0"
                                                IsReadOnly="True"
                                                HorizontalAlignment="Left" BorderBrush="{x:Null}"
                                                Visibility="{Binding Items.Count, Converter={StaticResource CountToVisibilityConverter}, Mode=OneWay, RelativeSource={RelativeSource Self}}"
                                                >
                                <DataGrid.Height>
                                    <MultiBinding Converter="{StaticResource RelativeAxisConverter}">
                                        <Binding ElementName="queryArea" Path="ActualHeight" />
                                        <Binding ElementName="queryEditorResizeWrapper" Path="ActualHeight"/>
                                    </MultiBinding>
                                </DataGrid.Height>
                            </DataGrid>
                           
                        </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </TabControl.ContentTemplate>
            </TabControl>
   
    </Grid>

</controls:MetroWindow>
